package com.peans.component;

import java.io.BufferedReader;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.peans.annotation.PropertyParam;
import com.peans.common.utils.mapBean.MapPropertyBean;

public class PropertyParamResolver implements HandlerMethodArgumentResolver {

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
        Class<?> klass = parameter.getParameterType();
        if (klass.isAssignableFrom(MapPropertyBean.class)) {
            Annotation[] as = parameter.getParameterAnnotations();
            for (Annotation a : as) {
                if (a.annotationType() == PropertyParam.class) {
                    return true;
                }
            }
        }
        return false;
	}

	   /**
     * 获取url参数
     * @return
     */
    protected Map<String, String> getParamsMap(HttpServletRequest hr) {
        Map<String, String[]> parasMap = hr.getParameterMap();
        Map<String, String> result = new HashMap<>();
        for (Map.Entry<String, String[]> entry : parasMap.entrySet()) {
            String paraName = entry.getKey();
            String[] paraValueArray = entry.getValue();
            String paraValue = (paraValueArray != null && paraValueArray.length > 0) ? paraValueArray[0] : null;
            if (paraValue != null) {
                result.put(paraName, paraValue);
            }
        }
        return result;
    }
	
	private String getRequestPayload(HttpServletRequest req) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = req.getReader();) {
            char[] buff = new char[1024];
            int len;
            while ((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
	
	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		HttpServletRequest hr = webRequest.getNativeRequest(HttpServletRequest.class);
		return getParamsMap(hr);
	}

}
